#include <iostream>
#include <map>
#include "Scene.h"
#include "Sphere.h"
#include "Plane.h"
#include "Triangle.h"

Scene::~Scene(){
	for(size_t i = 0; i < objects.size(); i++){
		delete objects[i];
	}
}

Scene::Scene(std::ifstream &inputFile){
	std::string field;
	std::map<std::string, bool> fieldsPresent;
	while(!inputFile.eof()){
		try{
			inputFile >> field;
		}
		catch(std::ifstream::failure e){// This is expected.
			break;
		}
		try{
			if(field.compare("NEAR") == 0 && !fieldsPresent["NEAR"]){
				inputFile >> near;
				fieldsPresent["NEAR"] = true;
				continue;
			}
			if(field.compare("LEFT") == 0 && !fieldsPresent["LEFT"]){
				inputFile >> left;
				fieldsPresent["LEFT"] = true;
				continue;
			}
			if(field.compare("RIGHT") == 0 && !fieldsPresent["RIGHT"]){
				inputFile >> right;
				fieldsPresent["RIGHT"] = true;
				continue;
			}
			if(field.compare("BOTTOM") == 0 && !fieldsPresent["BOTTOM"]){
				inputFile >> bottom;
				fieldsPresent["BOTTOM"] = true;
				continue;
			}
			if(field.compare("TOP") == 0 && !fieldsPresent["TOP"]){
				inputFile >> top;
				fieldsPresent["TOP"] = true;
				continue;
			}
			if(field.compare("RES") == 0 && !fieldsPresent["RES"]){
				inputFile >> xRes >> yRes;
				fieldsPresent["RES"] = true;
				continue;
			}
			if(field.compare("SPHERE") == 0) {
				objects.push_back(new Sphere(inputFile));
				continue;
			}
			if(field.compare("PLANE") == 0) {
				objects.push_back(new Plane(inputFile));
				continue;
			}
            if(field.compare("TRIANGLE") == 0) {
                objects.push_back(new Triangle(inputFile));
                continue;
            }
			if(field.compare("LIGHT") == 0) {
				lights.push_back(Light(inputFile));
				continue;
			}
			if(field.compare("BACK") == 0 && !fieldsPresent["BACK"]){
				backgroundColor = Color(inputFile);
				fieldsPresent["BACK"] = true;
				continue;
			}
			if(field.compare("AMBIENT") == 0 && !fieldsPresent["AMBIENT"]){
				ambientColor = Color(inputFile);
				fieldsPresent["AMBIENT"] = true;
				continue;
			}
			if(field.compare("OUTPUT") == 0 && !fieldsPresent["OUTPUT"]){
				inputFile >> outputFilename;
				if(outputFilename.size() > 20){
					outputFilename = outputFilename.substr(0, 16).append(".ppm");
				}
				fieldsPresent["OUTPUT"] = true;
				continue;
			}
		}
		catch(std::ifstream::failure e){
			if(inputFile.eof()){
				throw e;
			}
			else{
				std::cout << "Warning: input failure." << std::endl;
				inputFile.clear();
			}
		}
	}
	if(fieldsPresent.size() != 9){
		throw 0;
	}
}

